package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IndexServiceImpl implements IndexService {
    @Resource
    private ItemClient itemClient;
    @Resource
    private GoodsRepository goodsRepository;

    @Override
    public void createIndexAndMapping() {
        // 删除已经存在的索引库
        try {
            goodsRepository.deleteIndex();
        } catch (Exception e) {
            log.error("删除失败，可能索引库不存在！", e);
        }
        // 然后创建一个新的
        goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }
    //goods对象生成
    @Override
    public Goods buildGoods(SpuDTO spuDTO){
        Goods goods = new Goods();
        BeanUtils.copyProperties(spuDTO,goods);

        //suggestion
        ArrayList<String> suggestion = new ArrayList<>();
        String bName = spuDTO.getBrandName();
        String cName = spuDTO.getCategoryName().split("/")[2];
        int length = bName.indexOf("（") == -1 ? bName.length() : bName.indexOf("（");
        String sbName = bName.substring(0,length);
        suggestion.add(bName);
        suggestion.add(cName);
        suggestion.add(sbName+cName);
        suggestion.add(cName+sbName);
        goods.setSuggestion(suggestion);
        //categoryId
        goods.setCategoryId(spuDTO.getCid3());
        //specs
        List<SpecParamDTO> specParamDTOS = itemClient.querySpecsValues(spuDTO.getId(), true);
        List<Map<String, Object>> specs = new ArrayList<>();
        specParamDTOS.forEach(specParamDTO -> {
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("name",specParamDTO.getName());
            resultMap.put("value",chooseSegment(specParamDTO));
            specs.add(resultMap);
        });
        goods.setSpecs(specs);
        //image
        List<SkuDTO> skuDTOS = itemClient.querySkuBySpuId(spuDTO.getId());
        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(),","));
        //prices
        HashSet<Long> prices = new HashSet<>();
        skuDTOS.forEach(skuDTO -> prices.add(skuDTO.getPrice()));
        goods.setPrices(prices);
        //sold
        Long sold = 0L;
        for (SkuDTO skuDTO : skuDTOS) {
            sold += skuDTO.getSold();
        }
        goods.setSold(sold);
        //updateTime

        return goods;
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public void loadData(){
        createIndexAndMapping();
        //获取spu，转换为goods,保存
        int page = 1;
        while (true){
            PageDTO<SpuDTO> spu = itemClient.querySpuByPage(page, 50, null, null, null, null);
            if (spu.getTotalPage() == 0)break;
            List<Goods> goods = spu.getItems().stream().map(this::buildGoods).collect(Collectors.toList());
            goodsRepository.saveAll(goods);
            page++;
            if (page>spu.getTotalPage())break;
        }
    }

    @Override
    public void saveGoodsById(Long spuId) {
        //根据id查询spu
        List<SpuDTO> spuDTOS = this.itemClient.querySpuByPage(null, null, null, null, null, spuId).getItems();
        //es添加goods
        if (!CollectionUtils.isEmpty(spuDTOS)){
            Goods goods = buildGoods(spuDTOS.get(0));
            this.goodsRepository.save(goods);
        }
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        this.goodsRepository.deleteById(spuId);
    }
}
